function Point(x, y, val) {
  this.x = x;
  this.y = y;
  this.val = val;
}
/**
 * @param {number[][]} grid
 * @return {number}
 */
var swimInWater = function(grid) {
  // 方向, 用于坐标上下左右的移动
  let direction = [
    [1, 0],
    [0, 1],
    [0, -1],
    [-1, 0]
  ];
  let m = grid.length, n = grid[0].length;
  function bfs(mid) {
    // 用于判断某个位置是否已经访问/展开过
    if(grid[0][0] > mid) return false;
    let visited = new Array(m);
    for (let i = 0; i < m; i++) {
      visited[i] = new Array(n).fill(false);
    }
    let queue = [new Point(0, 0)];
    visited[0][0] = true;
    while(queue.length) {
      let x = queue[0].x, y = queue[0].y;
      queue.splice(0, 1);
      if(x == grid.length - 1 && y == grid[0].length - 1) {
        return true;
      }
      for(let i = 0; i < 4; i++) {
        let newX = x + direction[i][0];
        let newY = y + direction[i][1];
        if(newX < m && newX >= 0 && newY < n && newY >= 0 && !visited[newX][newY] && grid[newX][newY] <= mid) {
          visited[newX][newY] = true;
          queue.push(new Point(newX, newY));
        }
      }
    }
    return false;
  }
  let left = 0,
    right = 2500;
  while (left < right) {
    let mid = Math.floor((left + right) / 2);
    // console.log(`mid=${mid}, bfs(mid)=${bfs(mid)}`);
    if (bfs(mid)) {
      right = mid;
    } else {
      left = mid + 1;
    }
  }
  // bfs(22);
  return right;
};
let grid = [[0,2],[1,3]];
// console.log(swimInWater(grid));
grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]];
console.log(swimInWater(grid));
grid = [[3,2],[0,1]];
console.log(swimInWater(grid));
